--[[
FilePath: \Lua\View\UIActivitySpTask\UIActivitySpTask.lua
特殊任务活动
--]]

require 'View/UIBase/UIBase'

UIActivitySpTask = UIBase.New(PanelNames.UIActivitySpTask)
local _M = UIActivitySpTask

_M.hasInit = false
_M.hasInitView = false
_M.isPlaySkill = false
_M.hasInitTaskList = false

function _M.Init(func, id)
    _M.activeId = id
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Backbtn"), self.OnBack)
        self.bgTop = self:GetChild("bgTop");
        self.bgDown = self:GetChild("bgDown");
        self.title = self:GetChild("title");
        self.coinLb = self:GetChild("CoinLb");
        self.coinLb1 = self:GetChild("CoinLb1");
        self.bannerText = self:GetChild("bannerText");
        self.btnHelp = self:GetChild("help");
        self.btnItemBoxSp = self:GetChild("ItemBoxSp");
        self.taskList = self:GetChild("TaskList");
        self.itemBox = {};
        for i = 1, 6 do
            table.insert(self.itemBox, self:GetChild("ItemBox"..i));
        end
        self.btnDay = self:GetChild("btnDay");
        self.btnTotal = self:GetChild("btnTotal");
        self.btnHero = self:GetChild("BtnHero");
        self.model = self.btnHero:GetChild("n0");
        self.point ={};
        for i = 1, 5 do
            table.insert(self.point, self:GetChild("Point_"..i));
        end
        self.list = self:GetChild("List");
        self.startPoint = 0;
        self.endPoint = 1;
        _M.hasInit = true

        self.taskList.itemRenderer = self.RefreshItem;
        self.list.itemRenderer = self.RefreshTaskItem;
        self:addEvent()
    end
end

function _M:addEvent()
    self:RegisterEvent(Config.EventType.Fresh_Active,self.Refresh);
    self.btnHelp.onClick:Add(self.HelpTip, self)
    self.btnHero.onClick:Add(self.onClickHero, self)
    self.btnDay.onClick:Add(self.onClickDay, self)
    self.btnTotal.onClick:Add(self.onClickTotal, self)
end

function _M:removeEvent()
    self.btnHelp.onClick:Remove(self.HelpTip)
    self.btnHero.onClick:Remove(self.onClickHero)
    self.btnDay.onClick:Remove(self.onClickDay)
    self.btnDay.onClick:Remove(self.onClickTotal)
end

function _M:HelpTip()
    if self.tableData ~= nil and self.tableData.f_ExplainTitle ~= nil and self.tableData.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(self.tableData.f_ExplainTitle), tostring(self.tableData.f_ExplainText));
    end
end

function _M:onClickHero()
    if self.isPlaySkill then
        return;
    end
    if self.skillList == nil then
        return;
    end
    self.isPlaySkill = true;
    if self.heroTween then
        self.heroTween:Kill();
        self.heroTween = nil;
    end
    self:removeTimeCall();
    self:playHeroSkill(1);
end

function _M:onClickDay()

end

function _M:onClickTotal()
    if self.hasInitTaskList then
        return;
    end
    self.hasInitTaskList = true;
    self.list.numItems = 9;
end

function _M:playHeroSkill(index)
    if index > #self.skillList then
        self.actorMoveCompelet();
        self.isPlaySkill = false;
    else
        if self.aniObj ~= nil then
            local timeEnd = Util.PlayAction(self.aniObj, self.skillList[index], false);
            self.timeId = self:TimeCall(function()
                self:removeTimeCall();
                self:playHeroSkill(index + 1);
            end, timeEnd * 1000);
        end
    end
end

function _M:initView()
    self.btnItemBoxSp:GetChild("ItemBoxSpTips").text = getLanguage("终极大奖");
    if self.tableData ~= nil  then
        --[[
        local itemBoxIcon = self.tableData.f_ItemBoxIcon;
        if itemBoxIcon ~= nil and itemBoxIcon ~= "" then
            if type(itemBoxIcon) ~= "table" then
                itemBoxIcon = decodeJsonStrToTabel(itemBoxIcon)
            end
            for i = 1, #self.itemBox do
                local item = self.itemBox[i];
                local unLockIcon = item:GetChild("n8");
                local lockIcon = item:GetChild("n6");
                local rewardedIcon = item:GetChild("n7");
                unLockIcon.url = itemBoxIcon[1];
                lockIcon.url = itemBoxIcon[2];
                rewardedIcon.url = itemBoxIcon[3];
            end
        end
        local itemBoxSpIcon = self.tableData.f_ItemBoxSpIcon;
        if itemBoxSpIcon ~= nil and itemBoxSpIcon ~= "" then
            if type(itemBoxSpIcon) ~= "table" then
                itemBoxSpIcon = decodeJsonStrToTabel(itemBoxSpIcon)
            end
            local unLockIcon = self.btnItemBoxSp:GetChild("n10");
            local lockIcon = self.btnItemBoxSp:GetChild("n11");
            local rewardedIcon = self.btnItemBoxSp:GetChild("n12");
            unLockIcon.url = itemBoxSpIcon[1];
            lockIcon.url = itemBoxSpIcon[2];
            rewardedIcon.url = itemBoxSpIcon[3];
        end
        --]]
        local topBanner = self.tableData.f_TopBanner;
        if topBanner ~= nil and topBanner ~= "" then
            self.bgTop.url = topBanner;
        end
        local downBanner = self.tableData.f_DownBanner;
        if downBanner ~= nil and downBanner ~= "" then
            self.bgDown.url = downBanner;
        end
        self.title.text = getLanguage(self.tableData.f_Title);

        self.coinLb.visible = false;
        self.coinLb1.visible = false;
        local resourceShow = self.tableData.f_ResourceShow;
        if resourceShow ~= nil and resourceShow ~= "" then
            if type(resourceShow) ~= "table" then
                resourceShow = decodeJsonStrToTabel(resourceShow)
            end
            if resourceShow[1] ~= nil then
                self.coinLb.visible = true;
                local item1 = logicMgr.ItemManager.getItemConstDatabyModelId(resourceShow[1]);
                if item1 ~= nil then
                    self.coinLb.icon = EnumConst.AtlasPath.ItemAtlas..item1.icon;
                end
            end
            if resourceShow[2] ~= nil then
                self.coinLb1.visible = true;
                local item2 = logicMgr.ItemManager.getItemConstDatabyModelId(resourceShow[2]);
                if item2 ~= nil then
                    self.coinLb1.icon = EnumConst.AtlasPath.ItemAtlas..item2.icon;
                end
            end
        end

        -- 加载战斗小人
        self.skillList = nil;
        if self.tableData.f_SpineGrow ~= nil and self.tableData.f_SpineGrow ~= "" then
            if type(self.tableData.f_SpineGrow) ~= "table" then
                self.skillList = decodeJsonStrToTabel(self.tableData.f_SpineGrow)
            else
                self.skillList = self.tableData.f_SpineGrow;
            end
        end
        if self.tableData.f_Heroid ~= nil and self.tableData.f_Heroid ~= "" and tonumber(self.tableData.f_Heroid) > 0 then
            math.randomseed(tostring(os.time()):reverse():sub(1, 7));
            local path = HeroManager.GetHeroDrawingRolePath(self.tableData.f_Heroid);
            resMgr:LoadModelPrefab(path, function(go)
                if self.playRole ~= nil then
                    destroyImmediate(self.playRole);
                    self.playRole = nil
                end
                self.playRole = newObject(go);
                self.playRole:AddComponent(TCanvas)
                --self.playRole:AddComponent(TChangeSortingOrder)
                if self.drawWrapper == nil then
                    self.drawWrapper = GoWrapper.New()
                end
                self.drawWrapper:SetWrapTarget(self.playRole,false);
                Util.Lua_SetLocalPositionXYZ(self.playRole, 0, 0, 0);
                Util.Lua_SetLocalScaleXYZ(self.playRole, 88, 88, 88);
                self.model:SetNativeObject(self.drawWrapper);
                self.aniObj = Util.Lua_FindGameObject(self.playRole, "Animation") --self.playRole.transform:Find("Animation").gameObject;
                self.skeletonAnim = self.aniObj:GetComponent("SkeletonAnimation");
                logicMgr.EquipManager.setWeaponSkin(self.aniObj, self.tableData.f_Heroid, true);
                Util.PlayAction(self.aniObj, self:getAnimationName("idleFree"));

                self:removeTimeCall();
                self.timeId = self:TimeCall(self.heroIdleEnd, 3000);
            end)
        end
    end
end

function _M:getAnimationName(aniName)
    if self.modelName == nil then
        local heroInfo = dataTable.getRow("t_hero", self.tableData.f_Heroid)
        if heroInfo then
            self.modelName = heroInfo.f_HeroModel
        end
    end
    local str = G.dataTable["t_roleconfig"][self.modelName][aniName][1];
    local randomNames = string.split(str, ",");
    return randomNames[math.random(1, #randomNames)];
end

function _M:removeTimeCall()
    if self.timeId ~= nil then
        utimer.remove(self.timeId);
        self.timeId = nil;
    end
end

function _M:heroIdleEnd()
    self:removeTimeCall();
    local index = math.random(1, 5);
    if index == self.startPoint or index == self.endPoint or self.point[index] == nil then
        self:heroIdleEnd();
    else
        if self.aniObj ~= nil then
            self.startPoint = self.endPoint;
            self.endPoint = index;

            local speed = UICityRunAIManager.MOVE_SPEED * 30;
            local tempVec = Vector3.New(0, 0, 0);
            local tempPos = Vector3.New(0, 0, 0);
            tempPos:Set(self.btnHero.x, self.btnHero.y);
            tempVec:Set(self.point[index].x, self.btnHero.y);
            self.aniObj.transform.localEulerAngles = tempVec.x >= tempPos.x and Vector3.zero or Vector3.New(0, 180, 0);

            tempPos:Set(tempPos.x - tempVec.x, tempPos.y - tempVec.y);
            local len = tempPos:Magnitude();
            local time = len / speed;
            if self.heroTween then
                self.heroTween:Kill();
                self.heroTween = nil;
            end
            self.heroTween = self.btnHero:TweenMove(tempVec, time):SetEase(EaseType.Linear):OnComplete(function()
                self.startPoint = 0;
                self.actorMoveCompelet();
            end);
            Util.PlayAction(self.aniObj, self:getAnimationName("run"));
        end
    end
end

function _M.actorMoveCompelet()
    Util.PlayAction(_M.aniObj, _M:getAnimationName("idleFree"));

    _M:removeTimeCall();
    _M.timeId = _M:TimeCall(_M.heroIdleEnd, 3000);
end

-- 显示
function _M:OnEnable()
    self:Refresh();
end

function _M:Refresh()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            --self:OnBack();
            --return;
        end
    end

    if not self.hasInitView then
        self.hasInitView = true;
        self:initView();

        self.taskListIcon = nil;
        if self.tableData ~= nil then
            self.taskListIcon = self.tableData.f_TaskListIcon;
            if self.taskListIcon ~= nil and self.taskListIcon ~= "" then
                if type(self.taskListIcon) ~= "table" then
                    self.taskListIcon = decodeJsonStrToTabel(self.taskListIcon)
                end
            end
        end
    end

    local time = HelperFunc.GetServerTime();
    self.endCountDown = 0;
    --self.endCountDown = self.serverData.endTime - time;
    self:updateActiveCountDown();
    self:TimeCall(self.updateActiveCountDown, 1000, -1);
end

function _M:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    if self.endCountDown <= 0 then
        self.bannerText.text = getLanguage("Sys_ActivityEnd");
        self:RemoveTimeCall(self.updateActiveCountDown)
    else
        self.bannerText.text = string.format(getLanguage("Sys_ActivityTimeLeft"), HelperFunc.GetSurpTimeStr(self.endCountDown));
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M:updateData()
    self.taskList.numItems = 9;
end

function _M.RefreshItem(index, itemObj)
    local unLockIcon = itemObj:GetChild("n3");
    local lockIcon = itemObj:GetChild("n5");
    local rewardedIcon = itemObj:GetChild("n4");
    local drawTips = itemObj:GetChild("DrawTips");
    local itemIndex = tonumber(index) + 1;
    if _M.taskListIcon ~= nil then
        unLockIcon.url = _M.taskListIcon[1];
        lockIcon.url = _M.taskListIcon[2];
        rewardedIcon.url = _M.taskListIcon[3];
    end
    drawTips.text = tostring(itemIndex);
end

function _M:RefreshTaskItem(index, itemObj)

end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    self.hasInit = false
    self.hasInitView = false
    self.isPlaySkill = false
    self.hasInitTaskList = false
    self:RemoveTimeCall(self.updateActiveCountDown)
    self:removeTimeCall();
    if self.heroTween then
        self.heroTween:Kill();
        self.heroTween = nil;
    end

    if self.playRole ~= nil then
        destroy(self.playRole);
        self.playRole = nil;
    end
    if self.drawWrapper then
        self.drawWrapper:Dispose();
        self.drawWrapper = nil;
    end
end

return _M;